<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/6 0006
 * Time: 下午 5:06
 */
namespace App\Admin\Extensions;

use Encore\Admin\Grid;
use Encore\Admin\Grid\Exporters\AbstractExporter;
use Maatwebsite\Excel\Facades\Excel;

class ExcelExpoter extends AbstractExporter
{
    protected $head = [];
    protected $body = [];
    protected $field_arr = [];
    protected $config = [];

    public function setAttr($head, $body , $field_arr=[], $config=[])
    {
        $this->head = $head;
        $this->body = $body;
        $this->field_arr = $field_arr;
        $this->config = $config;
    }

    public function export()
    {
        set_time_limit(300);
        ini_set('memory_limit','528M');
        $filename = isset($this->config['filename'])?$this->config['filename']:'filename';
        Excel::create($filename, function($excel){
            $excel->sheet('sheet', function($sheet){
                $head = $this->head;
                $body = $this->body;
                $field_arr = $this->field_arr;
                $bodyRows = collect($this->getData())->map(function ($item)use($body, $field_arr) {
                    foreach ($body as $keyName){
                        $temp = array_get($item, $keyName);
                        if(array_key_exists($keyName, $field_arr)){
                            if(!is_array($field_arr[$keyName])){
                                $temp = $this->switchByKey($field_arr[$keyName], $temp);
                            }else{
                                $temp = $field_arr[$keyName][$temp];
                            }
                        }
                        $arr[] = $temp;
                        //$arr[] = array_get($item, $keyName);
                    }
                    return $arr;
                });
                $rows = collect([$head])->merge($bodyRows);
                $sheet->rows($rows);
            });
        })->export('xls');
    }

    private function switchByKey($key, $val)
    {
        switch ($key) {
            case 'date':
                return date('Y-m-d H:i', $val);
                break;
            case 'format':
                $val = htmlentities($val);
                $val = strip_tags($val);
//                $val = str_replace('=','',$val);
                return $val;
                break;
        }
    }

    /**
    例子
    $excel = new ExcelExpoter();
    $model = new Money();
    $excel->setAttr(
    ['id', '订单号', '创建时间','书名','用户id','支付状态','设备渠道','金额','支付类型'],
    ['id', 'no', 'ctime', 'g_book.title','uid','status','source','rmb','tid'],
    ['ctime'=>'date', 'status'=>$model->status_arr, 'tid'=>$model->tid_arr, 'source'=>$model->source_arr]
    );
    $grid->exporter($excel);

     **/

}
